package cn.anjubao.cp.api.config.security;

import cn.anjubao.cp.api.config.security.filter.LoginFilter;
import cn.anjubao.cp.api.config.security.filter.SessionFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SecurityConfig  extends WebSecurityConfigurerAdapter {

    @Autowired
    private SessionFilter sessionFilter;

    @Autowired
    private UserProvider userCheckProvider;

    @Autowired
    private AuthEntryPoint authEntryPoint;

    @Bean
    public LoginFilter loginFilter() throws Exception {
        return new LoginFilter(this.authenticationManager());
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(userCheckProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/test/**", "/user/decode", "/user/login", "/error").permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilterAfter(loginFilter(), UsernamePasswordAuthenticationFilter.class)
                .addFilterAfter(sessionFilter, UsernamePasswordAuthenticationFilter.class)
                //修改默认的ExceptionTranslationFilter中对异常的处理方法
                .exceptionHandling().authenticationEntryPoint(authEntryPoint);
    }
}
